import 'package:get/get.dart';
import 'package:flutter/material.dart';

import '../../models/tianyi_user.dart';
import '../../services/database_service.dart';
import '../../services/tianyi_cloud_service.dart';
import '../../services/file_manager_service.dart';
import '../../services/upload/upload_service.dart';
import '../../services/download/download_service.dart';
import '../../services/sync_service.dart';
import '../../services/notification_service.dart';
import '../../services/preferences_service.dart';

class MainController extends GetxController {
  final DatabaseService _databaseService = Get.find<DatabaseService>();
  final TianyiCloudService _cloudService = Get.find<TianyiCloudService>();
  final FileManagerService _fileManagerService = Get.find<FileManagerService>();
  final UploadService _uploadService = Get.find<UploadService>();
  final DownloadService _downloadService = Get.find<DownloadService>();
  final SyncService _syncService = Get.find<SyncService>();
  final NotificationService _notificationService = Get.find<NotificationService>();
  final PreferencesService _preferencesService = Get.find<PreferencesService>();
  
  // 当前用户
  final Rxn<TianyiUser> _currentUser = Rxn<TianyiUser>();
  TianyiUser? get currentUser => _currentUser.value;
  
  // 登录状态
  final RxBool _isLoggedIn = false.obs;
  bool get isLoggedIn => _isLoggedIn.value;
  
  // 当前选中的底部导航索引
  final RxInt _selectedIndex = 0.obs;
  int get selectedIndex => _selectedIndex.value;
  
  // 应用主题
  final Rx<ThemeMode> _themeMode = ThemeMode.system.obs;
  ThemeMode get themeMode => _themeMode.value;
  
  // 语言设置
  final Rx<Locale> _locale = const Locale('zh', 'CN').obs;
  Locale get locale => _locale.value;
  
  // 网络状态
  final RxBool _isOnline = true.obs;
  bool get isOnline => _isOnline.value;
  
  // 同步状态
  final RxBool _isSyncing = false.obs;
  bool get isSyncing => _isSyncing.value;
  
  // 上传/下载状态
  final RxBool _hasActiveTransfers = false.obs;
  bool get hasActiveTransfers => _hasActiveTransfers.value;
  
  // 存储使用情况
  final RxDouble _storageUsagePercentage = 0.0.obs;
  double get storageUsagePercentage => _storageUsagePercentage.value;
  
  @override
  void onInit() {
    super.onInit();
    _initializeApp();
    _setupListeners();
  }
  
  // 初始化应用
  Future<void> _initializeApp() async {
    try {
      // 加载用户偏好设置
      await _loadPreferences();
      
      // 检查登录状态
      await _checkLoginStatus();
      
      // 初始化通知服务
      await _notificationService.initialize();
      
      // 如果已登录，加载用户数据
      if (_isLoggedIn.value) {
        await _loadUserData();
      }
      
    } catch (e) {
      print('应用初始化失败: $e');
    }
  }
  
  // 设置监听器
  void _setupListeners() {
    // 监听同步状态变化
    ever(_syncService.syncStatus.obs, (SyncStatus status) {
      _isSyncing.value = status == SyncStatus.syncing;
    });
    
    // 监听上传/下载状态变化
    ever(_uploadService.activeUploads.obs, (_) => _updateTransferStatus());
    ever(_downloadService.activeDownloads.obs, (_) => _updateTransferStatus());
  }
  
  // 加载偏好设置
  Future<void> _loadPreferences() async {
    final theme = _preferencesService.getThemeMode();
    _themeMode.value = theme;
    
    final language = _preferencesService.getLanguage();
    _locale.value = Locale(language);
  }
  
  // 检查登录状态
  Future<void> _checkLoginStatus() async {
    try {
      final user = await _databaseService.getCurrentUser();
      if (user != null && user.isSessionValid) {
        _currentUser.value = user;
        _isLoggedIn.value = true;
        
        // 验证会话是否仍然有效
        final isValid = await _cloudService.validateSession();
        if (!isValid) {
          await logout();
        }
      } else {
        _isLoggedIn.value = false;
      }
    } catch (e) {
      print('检查登录状态失败: $e');
      _isLoggedIn.value = false;
    }
  }
  
  // 加载用户数据
  Future<void> _loadUserData() async {
    try {
      if (_currentUser.value != null) {
        // 更新存储使用情况
        _updateStorageUsage();
        
        // 刷新文件列表
        await _fileManagerService.refreshCurrentDirectory();
      }
    } catch (e) {
      print('加载用户数据失败: $e');
    }
  }
  
  // 登录
  Future<bool> login() async {
    try {
      final user = await _cloudService.loginWithQRCode();
      if (user != null) {
        _currentUser.value = user;
        _isLoggedIn.value = true;
        
        await _loadUserData();
        
        // 显示登录成功通知
        await _notificationService.showLoginSuccessNotification(user.nickname);
        
        return true;
      }
      return false;
    } catch (e) {
      print('登录失败: $e');
      Get.snackbar(
        '登录失败',
        e.toString(),
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
      return false;
    }
  }
  
  // 登出
  Future<void> logout() async {
    try {
      // 取消所有正在进行的传输
      await _cancelAllTransfers();
      
      // 清除用户数据
      if (_currentUser.value != null) {
        await _databaseService.deleteUser(_currentUser.value!.userId);
      }
      
      _currentUser.value = null;
      _isLoggedIn.value = false;
      
      // 清除文件管理器状态
      _fileManagerService.clearState();
      
      Get.snackbar(
        '已登出',
        '您已成功登出',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.green,
        colorText: Colors.white,
      );
      
    } catch (e) {
      print('登出失败: $e');
    }
  }
  
  // 切换底部导航
  void changeTabIndex(int index) {
    _selectedIndex.value = index;
  }
  
  // 切换主题
  void changeTheme(ThemeMode mode) {
    _themeMode.value = mode;
    _preferencesService.setThemeMode(mode);
    Get.changeThemeMode(mode);
  }
  
  // 切换语言
  void changeLanguage(String languageCode) {
    final locale = Locale(languageCode);
    _locale.value = locale;
    _preferencesService.setLanguage(languageCode);
    Get.updateLocale(locale);
  }
  
  // 开始同步
  Future<void> startSync() async {
    if (!_isLoggedIn.value) {
      Get.snackbar(
        '未登录',
        '请先登录后再进行同步',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.orange,
        colorText: Colors.white,
      );
      return;
    }
    
    try {
      await _syncService.startSync();
    } catch (e) {
      Get.snackbar(
        '同步失败',
        e.toString(),
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
    }
  }
  
  // 暂停同步
  void pauseSync() {
    _syncService.pauseSync();
  }
  
  // 取消所有传输
  Future<void> _cancelAllTransfers() async {
    // 取消所有上传任务
    for (final task in _uploadService.activeUploads) {
      await _uploadService.cancelUpload(task.id);
    }
    
    // 取消所有下载任务
    for (final task in _downloadService.activeDownloads) {
      await _downloadService.cancelDownload(task.id);
    }
  }
  
  // 更新传输状态
  void _updateTransferStatus() {
    _hasActiveTransfers.value = 
        _uploadService.activeUploads.isNotEmpty || 
        _downloadService.activeDownloads.isNotEmpty;
  }
  
  // 更新存储使用情况
  void _updateStorageUsage() {
    if (_currentUser.value != null) {
      _storageUsagePercentage.value = _currentUser.value!.usagePercentage;
    }
  }
  
  // 刷新用户信息
  Future<void> refreshUserInfo() async {
    if (!_isLoggedIn.value) return;
    
    try {
      final userInfo = await _cloudService.getUserInfo();
      if (userInfo != null) {
        _currentUser.value = userInfo;
        await _databaseService.updateUser(userInfo);
        _updateStorageUsage();
      }
    } catch (e) {
      print('刷新用户信息失败: $e');
    }
  }
  
  // 检查网络状态
  void updateNetworkStatus(bool isOnline) {
    _isOnline.value = isOnline;
    
    if (!isOnline) {
      Get.snackbar(
        '网络断开',
        '网络连接已断开，部分功能可能无法使用',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.orange,
        colorText: Colors.white,
        duration: const Duration(seconds: 3),
      );
    }
  }
  
  // 显示错误信息
  void showError(String title, String message) {
    Get.snackbar(
      title,
      message,
      snackPosition: SnackPosition.BOTTOM,
      backgroundColor: Colors.red,
      colorText: Colors.white,
      duration: const Duration(seconds: 4),
    );
  }
  
  // 显示成功信息
  void showSuccess(String title, String message) {
    Get.snackbar(
      title,
      message,
      snackPosition: SnackPosition.BOTTOM,
      backgroundColor: Colors.green,
      colorText: Colors.white,
      duration: const Duration(seconds: 3),
    );
  }
  
  // 显示信息
  void showInfo(String title, String message) {
    Get.snackbar(
      title,
      message,
      snackPosition: SnackPosition.BOTTOM,
      backgroundColor: Colors.blue,
      colorText: Colors.white,
      duration: const Duration(seconds: 3),
    );
  }
  
  // 获取应用统计信息
  Map<String, dynamic> getAppStatistics() {
    return {
      'isLoggedIn': _isLoggedIn.value,
      'currentUser': _currentUser.value?.toJson(),
      'storageUsage': _storageUsagePercentage.value,
      'isSyncing': _isSyncing.value,
      'hasActiveTransfers': _hasActiveTransfers.value,
      'uploadTasks': _uploadService.totalTasks,
      'downloadTasks': _downloadService.totalTasks,
      'syncStatistics': _syncService.getSyncStatistics(),
    };
  }
  
  // 清理缓存
  Future<void> clearCache() async {
    try {
      // 清理数据库缓存
      await _databaseService.clearCache();
      
      // 清理文件缓存
      // 这里可以添加清理临时文件的逻辑
      
      showSuccess('清理完成', '缓存已清理');
    } catch (e) {
      showError('清理失败', e.toString());
    }
  }
  
  // 导出设置
  Future<Map<String, dynamic>> exportSettings() async {
    return {
      'theme': _themeMode.value.toString(),
      'language': _locale.value.languageCode,
      'preferences': await _preferencesService.exportSettings(),
    };
  }
  
  // 导入设置
  Future<void> importSettings(Map<String, dynamic> settings) async {
    try {
      // 导入主题设置
      if (settings.containsKey('theme')) {
        final themeString = settings['theme'] as String;
        final theme = ThemeMode.values.firstWhere(
          (mode) => mode.toString() == themeString,
          orElse: () => ThemeMode.system,
        );
        changeTheme(theme);
      }
      
      // 导入语言设置
      if (settings.containsKey('language')) {
        final language = settings['language'] as String;
        changeLanguage(language);
      }
      
      // 导入偏好设置
      if (settings.containsKey('preferences')) {
        await _preferencesService.importSettings(settings['preferences']);
      }
      
      showSuccess('导入成功', '设置已导入');
    } catch (e) {
      showError('导入失败', e.toString());
    }
  }
}